package com.ruoyi.ade.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ade.domain.AdeKnowledge;
import com.ruoyi.ade.domain.Emr;
import com.ruoyi.ade.llm.model.Ade;
import com.ruoyi.ade.mapper.AdeKnowledgeMapper;
import com.ruoyi.ade.mapper.EmrMapper;
import com.ruoyi.ade.service.IAdeKnowledgeMgtService;
import com.ruoyi.ade.tool.AdeCompareUtils;
import com.ruoyi.ade.tool.AdeJsonFormatUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ADE KnowledgeService业务层处理
 *
 * @author wxh
 * @date 2025-06-04
 */
@Service
@Slf4j
public class AdeKnowledgeMgtServiceImpl implements IAdeKnowledgeMgtService {
    @Autowired
    private AdeKnowledgeMapper adeKnowledgeMapper;

    @Autowired
    private EmrMapper emrMapper;

    private static boolean formatting = false;
    private static boolean importing = false;

    /**
     * 导入ADE Knowledge ， 从标注的结果中(ADE Corpus)，将结果中的数据导入ade_knowledge表中
     * @return
     */
    public boolean importAdeKnowledge(){
        if(importing) return false;
        importing = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Emr cond = new Emr();
                cond.setStatus("1");

                List<AdeKnowledge> adeKnowledges = new ArrayList<>();
                List<AdeKnowledge> list = adeKnowledgeMapper.selectAdeKnowledgeList(new AdeKnowledge());
                for(AdeKnowledge adeKnowledge : list){
                    if("{}".equals(adeKnowledge.getAde())) continue;
                    adeKnowledges.add(adeKnowledge);
                }
                log.info("Get Ade Knowledge size:{}", adeKnowledges.size());
                List<Emr> emrs = emrMapper.selectEmrList(cond);
                log.info("Checked EMRs:{}", emrs.size());

                for (Emr emr : emrs) {
                    if("[]".equals(emr.getAdes())) continue;
                    List<Ade> ades = JSONArray.parseArray(emr.getAdes(), Ade.class);
                    if(ades.size() == 0)continue;
                    for (Ade ade : ades) {
                        if(ade.getSentence() == null) continue;
                        if(compare(adeKnowledges, ade)){
                            AdeKnowledge r = new AdeKnowledge();
                            r.setAde(JSONObject.toJSONString(ade));
                            r.setText(ade.getSentence());
                            r.setStatus("0");
                            adeKnowledgeMapper.insertAdeKnowledge(r);
                            adeKnowledges.add(r);
                            log.info("New Ade Knowledge:"+r.getAde());
                        }
                    }
                }
            }
        }).start();
        log.info("Finish Import Ade Knowledges");
        return true;
    }

    private boolean compare(List<AdeKnowledge> adeKnowledges, Ade ade){
        for(AdeKnowledge tmp : adeKnowledges){
            Ade ref = JSONObject.parseObject(tmp.getAde(),Ade.class);
            if(ref.getSentence() == null) continue;
            String  r= AdeCompareUtils.compare(ref,ade);
            if(AdeCompareUtils.ADE_SAME.equals(r)){
                return false;
            }
        }
        return true;
    }


    /**
     * 格式化ADE Knowledge
     *
     * @return
     */
    public boolean format() {
        if (formatting) return false;
        formatting = true;

        new Thread(new Runnable() {
            public void run() {
                try {
                    List<AdeKnowledge> adeKnowledges = adeKnowledgeMapper.selectAdeKnowledgeList(new AdeKnowledge());
                    for (AdeKnowledge adeKnowledge : adeKnowledges) {

                        Ade ade = JSONObject.parseObject(adeKnowledge.getAde(), Ade.class);

                        //判断是否合规
                        if (!AdeJsonFormatUtils.isvalidate(ade)) {  //如果不合规
                            AdeKnowledge cond = new AdeKnowledge();
                            cond.setId(adeKnowledge.getId());
                            cond.setStatus("0");
                            adeKnowledgeMapper.updateAdeKnowledge(cond);
                            continue;
                        }
                        //合规前提下 做药物实体的规范化处理    true-表示做了处理
                        if(AdeJsonFormatUtils.formatDrugs(ade)){
                            AdeKnowledge r = new AdeKnowledge();
                            r.setId(adeKnowledge.getId());
                            r.setAde(JSONObject.toJSONString(ade));
                            adeKnowledgeMapper.updateAdeKnowledge(r);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                formatting = false;
            }
        }).start();
        return true;
    }


    /**
     * 查询ADE Knowledge
     *
     * @param id ADE Knowledge主键
     * @return ADE Knowledge
     */
    @Override
    public AdeKnowledge selectAdeKnowledgeById(Long id) {
        return adeKnowledgeMapper.selectAdeKnowledgeById(id);
    }

    /**
     * 随机ADE Knowledge
     * @param adeKnowledge
     * @return
     */
    public AdeKnowledge selectOneRandomAdeKnowledge(AdeKnowledge adeKnowledge){
        return adeKnowledgeMapper.selectOneRandomAdeKnowledge(adeKnowledge);
    }

    /**
     * 查询ADE Knowledge列表
     *
     * @param adeKnowledge ADE Knowledge
     * @return ADE Knowledge
     */
    @Override
    public List<AdeKnowledge> selectAdeKnowledgeList(AdeKnowledge adeKnowledge) {
        return adeKnowledgeMapper.selectAdeKnowledgeList(adeKnowledge);
    }

    /**
     * 新增ADE Knowledge
     *
     * @param adeKnowledge ADE Knowledge
     * @return 结果
     */
    @Override
    public int insertAdeKnowledge(AdeKnowledge adeKnowledge) {
        return adeKnowledgeMapper.insertAdeKnowledge(adeKnowledge);
    }

    /**
     * 修改ADE Knowledge
     *
     * @param adeKnowledge ADE Knowledge
     * @return 结果
     */
    @Override
    public int updateAdeKnowledge(AdeKnowledge adeKnowledge) {
        return adeKnowledgeMapper.updateAdeKnowledge(adeKnowledge);
    }

    /**
     * 批量删除ADE Knowledge
     *
     * @param ids 需要删除的ADE Knowledge主键
     * @return 结果
     */
    @Override
    public int deleteAdeKnowledgeByIds(Long[] ids) {
        return adeKnowledgeMapper.deleteAdeKnowledgeByIds(ids);
    }

    /**
     * 删除ADE Knowledge信息
     *
     * @param id ADE Knowledge主键
     * @return 结果
     */
    @Override
    public int deleteAdeKnowledgeById(Long id) {
        return adeKnowledgeMapper.deleteAdeKnowledgeById(id);
    }
}
